import React, { FC, useState } from 'react';
import {
  EditorState,
  RichUtils,
  convertFromHTML,
  ContentState,
  convertToRaw,
} from 'draft-js';
import 'draft-js/dist/Draft.css';
import Editor from '@draft-js-plugins/editor';
import draftToMarkdown from 'draftjs-to-markdown';
import MarkdownIt from 'markdown-it';

const Editor_: any = Editor;

const Draft: FC = () => {
  const sampleMarkup =
    '<b>Bold text</b>, <i>Italic text</i><br/ ><br />' +
    '<a href="http://www.facebook.com">Example link</a>' +
    '<h1>Hello JAVA</h1>';

  const blocksFromHTML = convertFromHTML(sampleMarkup);

  const state = ContentState.createFromBlockArray(
    blocksFromHTML.contentBlocks,
    blocksFromHTML.entityMap
  );

  const [editorState, setEditorState] = useState<any>(
    EditorState.createWithContent(state)
  );

  // const rawContentState = convertToRaw(editorState.getCurrentContent());
  // // 将数据转化为MarkDown的数据格式
  // const markup = draftToMarkdown(rawContentState, {});

  const onChange = (editorState: any) => {
    const rawContentState = convertToRaw(editorState.getCurrentContent());
    const markup = draftToMarkdown(rawContentState, {});
    const md = new MarkdownIt();
    const result = md.render(markup);
    const blocksFromHTML = convertFromHTML(result);
    const state = ContentState.createFromBlockArray(
      blocksFromHTML.contentBlocks,
      blocksFromHTML.entityMap
    );
    console.log(result, state, editorState);

    setEditorState(editorState);
  };

  /*
    RichUtils包含有关 Web 编辑器可用的核心键命令的信息，例如 Cmd+B（粗体）、Cmd+I（斜体）等。
    我们可以通过 prop 观察和处理按键命令handleKeyCommand，并将它们挂钩RichUtils以应用或删除所需的样式。
  */
  const handleKeyCommand = (command: any, editorState: any) => {
    const newState = RichUtils.handleKeyCommand(editorState, command);

    if (newState) {
      onChange(newState);
      return 'handled';
    }
    return 'not-handled';
  };

  return (
    <>
      <button
        onClick={() => {
          onChange(RichUtils.toggleInlineStyle(editorState, 'BOLD'));
        }}
      >
        粗体
      </button>
      <Editor_
        editorState={editorState}
        onChange={onChange}
        handleKeyCommand={handleKeyCommand}
        // plugins={plugins}
      />
    </>
  );
};

export default Draft;
